# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(data.table)
library(optparse)
library(ropls)
library(magrittr)
library(tidyverse)
library(extrafont)

option_list <- list(
  make_option("--i", default = "AllMet_with_Anno.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--mc", default = "meta_color.txt", type = "character", help = "metabolite color file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--pc", default = "groupBar_plot_config.txt", type = "character", help = "config file")

)
opt <- parse_args(OptionParser(option_list = option_list))
font_import(paths = c("/usr/share/fonts/myFonts"),recursive =F, prompt = F)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/parse_config.R"))
fontFamily <- configGet(plotConfigData, "fontFamily")
baseFamily <- fontFamily

sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  select(c("SampleID", "ClassNote"))

sampleIds <- sampleInfo %>%
  .$SampleID

data <- read_tsv(opt$i) %>%
  select(-c("HMDB", "KEGG", "Metabolite")) %>%
  select(c("Class", sampleIds))

df <- data %>%
  group_by(Class) %>%
  summarise_all(sum) %>%
  gather("SampleID", "Value", -Class) %>%
  spread(Class, "Value") %>%
  left_join(sampleInfo, by = c("SampleID")) %>%
  group_by(ClassNote) %>%
  summarise_at(vars(-"SampleID"), sum) %>%
  gather("Class", "Value", -ClassNote) %>%
  spread(ClassNote, "Value") %>%
  mutate_at(vars(-"Class"), function(x) { x * 100 / sum(x) }) %>%
  gather("Sample", "Value", -Class) %>%
  spread(Class, "Value")

metaColDf <- read_tsv(opt$mc) %>%
  select(c("Class", "col"))
metaCols <- metaColDf %>%
  deframe()

pdf <- df %>%
  gather("Class", "Value", -Sample) %>%
  arrange(desc(Value)) %>%
  mutate(Class = factor(Class, levels = unique(Class)),
         Sample = factor(Sample, levels = unique(sampleInfo$ClassNote)))


outDf <- pdf %>%
  spread(Sample, "Value")

write_csv(outDf, "Class_Barplot_by_Group.csv")

defaultWidth <- 9 + max(0, length(unique(sampleInfo$ClassNote)) - 2) * 0.1

finalWidth <- getFinalWidth(width, defaultWidth, opt$pc)

pdf("Class_Barplot_by_Group.pdf", width = finalWidth, height = height)

yBreaks <- seq(0, 100, by = 25)

pData <- read_csv("Class_Barplot_by_Group_Test.csv") %>%
  rowwise() %>%
  do({
    result <- as_tibble(.)
    p <- result["P"]
    str <- if (p < 0.05 && p >= 0.01) {
      "*"
    }else if (p < 0.01 && p >= 0.001) {
      "**"
    }else if (p < 0.001) "***" else ""
    result$label <- str_c(result$Class, " ", str)
    result
  }) %>%
  ungroup() %>%
  arrange(factor(Class, levels = unique(pdf$Class)))

p <- ggplot(pdf, mapping = aes(x = Sample, y = Value, fill = Class, label = Class)) +
  xlab("") +
  ylab("Relative Abundance(%)") +
  theme_minimal(base_size = 8.8, base_family = baseFamily) +
  theme(axis.text.x = element_text(size = 14), panel.grid.minor = element_blank(),
        axis.text.y = element_text(size = 15), legend.position = 'right', panel.grid.major.x = element_blank(),
        panel.grid.major.y = element_line(size = 0.5, colour = "#D8D8D8"),
        panel.border = element_blank(), axis.title.y = element_text(size = 15),
        legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'), axis.ticks = element_line(colour = "black", size = 0.5),
        legend.text = element_text(size = 8), axis.title.x = element_text(size = 11), legend.key.size = unit(1, "line"),
        axis.line = element_blank(), plot.margin = unit(c(0.5, 0.5, 0.5, 0.5), "cm")
  ) +
  geom_col(width = 0.25) +
  scale_fill_manual("", values = metaCols, labels = pData$label, breaks = pData$Class) +
  scale_y_continuous(breaks = yBreaks)

p <- getBasicPlotArg(p)

plotConfigData

if (!is.na(legendTitle)) {
  p <- p +
    guides(fill = guide_legend(title = legendTitle))
}

p

dev.off()
